package ui;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.Point;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

import com.alee.laf.tabbedpane.TabStretchType;
import com.alee.laf.tabbedpane.TabbedPaneStyle;
import com.alee.laf.tabbedpane.WebTabbedPane;

import bean.Files;
import bean.Folders;
import service.IFileService;
import service.impl.IFileServiceImpl;
import utils.PictureUtil;


public class MainUI extends JDialog{
	/** 主面板 */
	private JPanel content;
	/** 搜索面板*/
	private SearchPanel searchPanel;
	/** 设置按钮 */
	private JLabel settingButton;
	/** 文件面板*/
	private JPanel fileInfo;
	/** 选项卡面板 */
	private WebTabbedPane menuInfo;
	/** 文件列表子类面板 */
	private FilePanel filePanel;
	/** 面板默认背景色 */
	private static Color defaultBgColor = Color.WHITE;
	/** 坐标（用于记录鼠标拖拽时，鼠标按下那一刻的坐标） */
	private Point point = new Point();
	

	
	private Folders folders;
	private Files files;
	private TrayIcon icon;
	private SystemTray tray;
	
	private IFileService ifileservice=new IFileServiceImpl();
	
	public static MainUI getInstance() {
		MainUI inst = new MainUI();
		inst.setLocationRelativeTo(null);
		inst.setVisible(true);
		inst.requestFocus();
		return inst;
	}
	
	public MainUI() {
	    super();        
	    initGUI();
	    initTrayIcon();
	    initListener();
	    initDragAndDrop();
	    
	    // 添加窗口透明度和背景色设置
	    //setBackground(new Color(0, 0, 0, 51)); // 0.2透明度黑色 (51/255≈0.2)
	    //setOpacity(1f);
	}
	

	private void initGUI() {
	    setSize(300, 400);
	    setAlwaysOnTop(true);
	    setUndecorated(true);
	    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
	    
	    // 设置窗口透明度和背景色
	    setBackground(new Color(0, 0, 0, 51));
	    setOpacity(0.7f);
	    
	    // 主面板
	    content = new JPanel();
	    content.setLayout(null);
	    content.setBackground(new Color(0, 0, 0, 51)); // 半透明黑色
	    content.setOpaque(false); // 必须设置为不透明才能显示透明度
	    getContentPane().add(content, BorderLayout.CENTER);
	    
	    // 搜索面板
	    searchPanel = new SearchPanel(ifileservice,menuInfo);
	    searchPanel.setBackground(new Color(0, 0, 0, 51));
	    searchPanel.setOpaque(false);
	    content.add(searchPanel);
	    searchPanel.setBounds(0, 3, 250, 32);
	    
	    // 设置按钮
	    settingButton = new JLabel("设置");
	    settingButton.setForeground(Color.WHITE); // 设置文字为白色
	    settingButton.setBackground(new Color(0, 0, 0, 51));
	    settingButton.setOpaque(false);
	    settingButton.setBounds(254,3,40,30);
	    content.add(settingButton);
	    
	    // 文件面板
	    fileInfo = new JPanel();
	    fileInfo.setBackground(new Color(0, 0, 0, 51));
	    fileInfo.setOpaque(false);
	    content.add(fileInfo);
	    fileInfo.setLayout(new BorderLayout());
	    fileInfo.setBounds(0, 35, 300, 370);
	    
	    // 选项卡面板
	    menuInfo = new WebTabbedPane();
	    fileInfo.add(menuInfo, BorderLayout.CENTER);
	    menuInfo.setOpaque(false);
	    menuInfo.setTabbedPaneStyle(TabbedPaneStyle.attached);
	    menuInfo.setTabStretchType(TabStretchType.always);
	    menuInfo.setTopBg(new Color(0, 0, 0, 30)); // 更透明的黑色
	    menuInfo.setBottomBg(new Color(0, 0, 0, 80));
	    menuInfo.setSelectedTopBg(new Color(0, 0, 0, 50));
	    menuInfo.setSelectedBottomBg(new Color(0, 0, 0, 50));
	    menuInfo.setBackground(new Color(0, 0, 0, 80));
	    menuInfo.setForeground(Color.WHITE); // 设置文字为白色
	    menuInfo.setBorder(BorderFactory.createLineBorder(new Color(100, 100, 100, 100)));
	    
	    // 显示文件列表
	    refreshFileList();
	}
	
	private void initListener() {
		// 主窗体事件-拖动
		this.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				point.x = e.getX();
				point.y = e.getY();
			}
		});
		this.addMouseMotionListener(new MouseAdapter() {
			@Override
			public void mouseDragged(MouseEvent e) {
				Point p = getLocation();
				setLocation(p.x + e.getX() - point.x, p.y + e.getY() - point.y);
			}
		});
		
		//选项卡鼠标右键点击事件
		menuInfo.addMouseListener(new MouseAdapter() {
		    @Override
		    public void mouseClicked(MouseEvent e) {
		        if (SwingUtilities.isRightMouseButton(e)) {
		            // 获取鼠标点击位置的选项卡索引
		            int tabIndex = menuInfo.indexAtLocation(e.getX(), e.getY());
		            if (tabIndex != -1) { // 确保点击的是选项卡
		                // 获取对应的 Folder 对象（FilePanel 存储了 Folder）
		                FilePanel filePanel = (FilePanel) menuInfo.getComponentAt(tabIndex);
		                Folders folder = filePanel.getFolder();
		                JPopupMenu popupMenu = new JPopupMenu();
		                // 1. 新建文件夹
		                JMenuItem newItem = new JMenuItem("新建选项");
		                newItem.addActionListener(ae -> {
		                    System.out.println("新建选项");
		                    Folders newFolder=ifileservice.addFolder("newFolder");
		                    FilePanel newFilePanel = new FilePanel(newFolder);		                    		                    
		                    menuInfo.addTab(newFolder.getFolderName(), newFilePanel);		                    
		                    //自动切换到新选项卡
		                    menuInfo.setSelectedIndex(menuInfo.getTabCount() - 1);
		                });
		                popupMenu.add(newItem);
		                
		                // 2. 粘贴
		                JMenuItem pasteItem = new JMenuItem("粘贴");
		                pasteItem.addActionListener(ae -> pasteFilesFromClipboard(menuInfo,folder.getFolderId()));
		                popupMenu.add(pasteItem);
		                
		                // 2. 删除文件夹
		                JMenuItem deleteItem = new JMenuItem("删除当前选项");
		                deleteItem.addActionListener(ae -> {
		                    System.out.println("删除当前选项：" + folder.getFolderName());
		                    ifileservice.removeFolder(folder.getFolderId()); // 传入 Folder 名称
		                    menuInfo.remove(tabIndex); // 移除选项卡
		                });
		                popupMenu.add(deleteItem);
		                
		                // 3. 修改文件夹名字"
		                JMenuItem renameItem = new JMenuItem("修改名字");
		                renameItem.addActionListener(ae -> {
		                    String newName = JOptionPane.showInputDialog(menuInfo,"输入新名称", folder.getFolderName());
		                    if (newName != null && !newName.trim().isEmpty()) {
		                        folder.setFolderName(newName); // 更新 Folder 对象
		                        menuInfo.setTitleAt(tabIndex, newName); // 更新名称
		                        // 更新到数据存储文件
		                        ifileservice.updateFolder(folder.getFolderId(), newName);
		                    }
		                });
		                popupMenu.add(renameItem);
		                
		             // 4. 导入文件
		                JMenuItem addFileItem = new JMenuItem("添加文件");
		                addFileItem.addActionListener(ae -> {
		                    // 创建文件选择器
		                    JFileChooser fileChooser = new JFileChooser();
		                    fileChooser.setDialogTitle("选择要添加的文件");
		                    fileChooser.setMultiSelectionEnabled(false); // 单文件选择
		                    // 显示文件选择对话框
		                    int result = fileChooser.showOpenDialog(menuInfo);
		                    if (result == JFileChooser.APPROVE_OPTION) {
		                        File selectedFile = fileChooser.getSelectedFile();
		                        // 读取文件内容
								String filename=selectedFile.getName();
								String filepath=selectedFile.getPath();
								String fileFolderId=folder.getFolderId();
								
								// 创建新的 Files 对象
								Files newFile = new Files(filename,filepath,fileFolderId);       
								
								// 调用服务层方法保存文件
								ifileservice.addFile(newFile,fileFolderId);					
								JOptionPane.showMessageDialog(menuInfo, "文件添加成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
								refreshFileList();
		                    }
		                });
		                popupMenu.add(addFileItem);
		                
		                popupMenu.show(menuInfo, e.getX(), e.getY());
		            }
		        }
		    }
		});
		
		//
		
	}


	private void initTrayIcon() {
		if (SystemTray.isSupported()) {
			try {
				tray = SystemTray.getSystemTray();
				icon = new TrayIcon(PictureUtil.getPicture("/jarvis_icon.png").getImage(), "jarvis");
				icon.setImageAutoSize(true); //自动适应大小
				icon.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseReleased(MouseEvent e) {
						if (e.getButton() == MouseEvent.BUTTON1) {
							setVisible(true);
							// 获取焦点
							requestFocus();
						}
					}
				});
				
				PopupMenu pm = new PopupMenu();
				MenuItem mit = new MenuItem("Exit");
				mit.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						tray.remove(icon);
						System.exit(0);
					}
				});
				pm.add(mit);
				icon.setPopupMenu(pm);
				tray.add(icon);
			} catch (AWTException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
	//文件列表刷新
	private void refreshFileList() {
		//先移除现有选项卡，再加载
	    while (menuInfo.getTabCount() > 0) {
	        menuInfo.remove(0); // 从第一个开始移除
	    }
		List<Folders> folderList=ifileservice.getFoldersList();
		for(Folders folder:folderList) {
			filePanel = new FilePanel(folder);
			menuInfo.addTab(folder.getFolderName(), filePanel);
		}
		//更新搜索面板的menuInfo对象的值，用于搜索后选中文件的定位
		searchPanel.setMenuInfo(menuInfo);
	}
	// 新增方法：初始化拖放功能
    private void initDragAndDrop() {
        // 为整个对话框设置拖放目标
        new DropTarget(this, new DropTargetAdapter() {
        	@Override
            public void dragEnter(DropTargetDragEvent dtde) {
                // 拖入时改变外观提示
                if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                    dtde.acceptDrag(DnDConstants.ACTION_COPY);
                    content.setBackground(new Color(220, 240, 255));
                } else {
                    dtde.rejectDrag();
                }
            }
            @Override
            public void dragExit(DropTargetEvent dte) {
                // 拖出时恢复外观
                content.setBackground(defaultBgColor);
            }
            @Override
            public void drop(DropTargetDropEvent dtde) {
                try {
                    // 接受拖放操作
                    dtde.acceptDrop(DnDConstants.ACTION_COPY);
                    // 获取拖放的文件列表
                    Transferable transferable = dtde.getTransferable();
                    if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                        @SuppressWarnings("unchecked")
                        List<File> droppedFiles = (List<File>) transferable.getTransferData(
                            DataFlavor.javaFileListFlavor);                   
                        // 获取当前选中的选项卡
                        int selectedIndex = menuInfo.getSelectedIndex();
                        if (selectedIndex >= 0) {
                            FilePanel currentPanel = (FilePanel) menuInfo.getComponentAt(selectedIndex);
                            Folders currentFolder = currentPanel.getFolder();                          
                            // 处理拖入的文件
                            handleDroppedFiles(droppedFiles, currentFolder);
                        }
                    }
                    dtde.dropComplete(true);
                } catch (Exception e) {
                    e.printStackTrace();
                    dtde.dropComplete(false);
                }
            }
        });
        
    }

    // 处理拖入的文件
    private void handleDroppedFiles(List<File> droppedFiles, Folders targetFolder) {
        for (File file : droppedFiles) {
            // 创建新的 Files 对象
            Files newFile = new Files(
                file.getName(),
                file.getAbsolutePath(),
                targetFolder.getFolderId()
            );           
            // 调用服务层方法保存文件
            ifileservice.addFile(newFile, targetFolder.getFolderId());
        }       
        // 刷新文件列表显示
        refreshFileList();       
        // 提示
        JOptionPane.showMessageDialog(this, 
            "成功添加 " + droppedFiles.size() + " 个文件到 " + targetFolder.getFolderName(),
            "文件添加成功", 
            JOptionPane.INFORMATION_MESSAGE);
    }
    /**
     * 从剪贴板粘贴文件到指定文件夹
     * @param parent 父组件（用于显示对话框）
     * @param folderId 目标文件夹ID
     */
    private void pasteFilesFromClipboard(Component parent, String folderId) {
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable transferable = clipboard.getContents(null);      
        if (transferable == null || !transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            JOptionPane.showMessageDialog(parent,"剪贴板中没有可粘贴的文件", "提示",JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        try {
            List<File> files = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor);
            File file = files.get(0); // 获取第一个文件
            Files f=new Files(file.getName(),file.getPath(),folderId);   
            System.out.println("进入粘贴处理--"+file.getName()+"---"+file.getPath());
            
            int successCount = 0;
            int skipCount = 0;
            
            // 检查文件是否已存在
            if (ifileservice.fileExist(file.getName(), folderId)) {
            	int option = JOptionPane.showConfirmDialog(parent,"文件 '" + file.getName() + "' 已存在，是否覆盖？",
            			"文件冲突",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.WARNING_MESSAGE);
            	if (option == JOptionPane.NO_OPTION) {
            		
            	} else if (option == JOptionPane.CANCEL_OPTION) {
            		
            	}else {
            		// json中替换
            		ifileservice.removeFile(f.getFileName());
                    ifileservice.addFile(f, folderId);
            	}
            }else {
            	// 保存到数据库
                ifileservice.addFile(f, folderId);
            }            
            // 刷新文件列表
            refreshFileList();
        } catch (UnsupportedFlavorException | IOException ex) {
            JOptionPane.showMessageDialog(
                parent,
                "读取剪贴板失败: " + ex.getMessage(),
                "错误",
                JOptionPane.ERROR_MESSAGE);
        }
    }
	
}
